package com.example.jimmerfast.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.digest.DigestUtil;
import com.example.jimmerfast.entity.User;
import com.example.jimmerfast.entity.dto.LoginReq;
import com.example.jimmerfast.error.UserLoginErrorCode;
import com.example.jimmerfast.error.UserLoginException;
import com.example.jimmerfast.service.UserService;
import com.example.jimmerfast.util.Constants;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.client.ThrowsAll;
import org.babyfish.jimmer.sql.ast.query.Example;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("auth")
public class AuthController {

    private final UserService userService;

    @ThrowsAll(UserLoginErrorCode.class)
    @PostMapping("/token")
    public SaTokenInfo token(@RequestBody LoginReq loginReq) {
        String password = loginReq.getPassword();
        loginReq.setPassword(null);
        List<User> userList = userService.findByExample(Example.of(loginReq.toEntity()));
        if (CollectionUtil.isEmpty(userList)) {
            throw UserLoginException.usernameNotFound("用户名不存在", "用户名不存在");
        }
        User user = userList.get(0);
        String s = DigestUtil.md5Hex(password);
        boolean passwordCheck = s.equalsIgnoreCase(user.password());
        if (passwordCheck) {
            StpUtil.login(user.id());
            StpUtil.getSession().set(Constants.USERINFO_SESSION_KEY, user);
        } else {
            throw UserLoginException.illegalUsernameOrPassword("用户名或密码错误", "用户名或密码错误");
        }

        return StpUtil.getTokenInfo();
    }
}
